# -*- coding: utf-8 -*-
# Create time: 2020-03-13 17:18
# Author:Rongzhikai
from email.header import Header
from conf import settings
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

smtp_server = settings.smtp_server
my_sender = settings.mail_user
my_pass = settings.password
receivers = settings.receivers
subject = settings.subject
report_dir = settings.REPORT_PATH


def send_report(message=None, files=None):
    msg = MIMEMultipart('related')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = my_sender
    msg['To'] = ','.join(receivers)

    # 邮件文本内容，可自己编辑可引用报告html，不过显示的网页内容，很low
    if message is not None:
        msg_content = MIMEText(message, _subtype='plain', _charset='utf-8')
    else:
        # 此处应调用最新测试报告文件html
        files_html = new_report(report_dir)
        with open(files_html, 'rb') as fp:
            mail_body = fp.read()
        msg_content = MIMEText(mail_body, _subtype='html', _charset='utf-8')

    # 添加附件
    if isinstance(files, list):
        for file in files:
            with open(file, 'rb') as fu:  # 添加附件
                sendfile = fu.read()
            addfile = MIMEText(sendfile, 'base64', 'utf-8')
            addfile['Content-Type'] = 'application/octet-stream'
            addfile["Content-Disposition"] = "attachment; filename={}".format(file.split("\\")[-1])
            msg.attach(addfile)
    msg.attach(msg_content)

    mail_server = smtplib.SMTP()
    mail_server.connect(smtp_server)
    mail_server.login(my_sender, my_pass)
    mail_server.sendmail(my_sender, receivers, msg.as_string())
    mail_server.close()
    print('Email has send out')


def new_report(reportpath):
    """获取最新的测试报告文件"""
    lists = os.listdir(reportpath)
    lists.sort(key=lambda fn: os.path.getmtime(reportpath + '\\' + fn))
    file_new = os.path.join(reportpath, lists[-1])
    return file_new

# files = ['E:\\PycharmProjects\\Apitest_automation\\report\\2020-03-15-13_00_39result.html', 'E:\\PycharmProjects\\Apitest_automation\\logs\\log.txt']
# send_report(message='666666')
